package com.rem.shiro.controller;

import com.rem.shiro.config.MyContext;
import com.rem.shiro.pojo.User;
import com.rem.shiro.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt 一般适用于前后端分离的项目 所以单独测试swagger
 *
 * @author Rem
 * @date 2021-04-15
 */

@Slf4j
@Validated
@CrossOrigin
@RequestMapping("jwt")
@RestController
public class TestJwtController {

    @PostMapping("/login")
    public Map<String, Object> login(User user) {
        log.info("用户名：[{}]", user.getUsername());
        log.info("密码：[{}]", user.getPassword());

        HashMap<String, Object> map = new HashMap<>();

        try {

            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));

            User loginUser = (User) subject.getPrincipal();


            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", loginUser.getId().toString());
            hashMap.put("sub", loginUser.getUsername());
            hashMap.put("username", loginUser.getUsername());
            hashMap.put("userId", loginUser.getId());

            String token = JwtUtils.generateToken(hashMap);


            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }


    @GetMapping("/test")
    public User test() {

        log.error("登陆成功后访问");
        return MyContext.getUser();
    }


}
